package com.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.room.Room;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private UserDatabase database;
    private UserDao dao;
    private TextView tv_content;
    private Button btn_insert, btn_delect, btn_update, btn_query,btn_clear;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_content = findViewById(R.id.tv_content);
        btn_insert = findViewById(R.id.btn_insert);
        btn_delect = findViewById(R.id.btn_delect);
        btn_update = findViewById(R.id.btn_update);
        btn_query = findViewById(R.id.btn_query);
        btn_clear= findViewById(R.id.btn_clear);
//        database = Room.databaseBuilder(this, UserDatabase.class, "user_data")
//                .allowMainThreadQueries()
//                .build();
//        dao = database.getUserDao();

        database = UserDatabase.getAppDatabase(this);
        dao = database.getUserDao();

        getAllData();


        btn_insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User u = new User("AA", "aaaa");
                dao.save(u);
                getAllData();
            }
        });


        btn_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User u = new User("AA", "aaaa");
                u.setId(9);
                dao.delect(u);
                getAllData();
            }
        });

        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User u = new User("AA", "123123");
                u.setId(10);
                dao.update(u);
                getAllData();
            }
        });

        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                getAllData();
            }
        });

        btn_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dao.clear();
                getAllData();
            }
        });

    }

    public void getAllData() {
        List<User> all = dao.getAll();
        String result = "";
        for (User u : all) {
            result += u.getId() + ": " + u.getName() + " : " + u.getAddress() + "\n";
        }
        tv_content.setText(result);
    }

}
